import { Input, message, Spin } from "antd";
import Axios, { AxiosResponse } from "axios";
import * as React from "react";
import { Map, Marker, PluginConfig, PluginList } from "react-amap";
// 导入一个没有声明文件的第三方库,使用require
const Autocomplete = require("react-amap-plugin-autocomplete");

export const defaultExtraForm: IExtraForm = {
  longitude: 0,
  latitude: 0,
  address: "",
  adcode: ""
};

export interface IExtraForm {
  longitude: number;
  latitude: number;
  address: string;
  adcode: string;
}

interface IProps {
  height: string;
  width: string;
  initPosition?: IPosition; //初始坐标
  callback: (params: IExtraForm) => void;
}
interface IPosition {
  longitude: number;
  latitude: number;
}

const defaultPosition = { longitude: 116.397454, latitude: 39.909166 };
const AMap: React.FC<IProps> = props => {
  const { height, width, callback, initPosition } = props;

  // 如果position为undefined或者position中的经纬度为null则显示默认经纬度
  const [position, setPosition] = React.useState<IPosition>(
    initPosition
      ? initPosition.longitude && initPosition.latitude
        ? { longitude: initPosition.longitude, latitude: initPosition.latitude }
        : defaultPosition
      : defaultPosition
  );

  const mapEvents = {
    created: (_: any) => {
      // //console.log(mapInstance);
    },
    //在地图上任意点击时的回调
    click: (e: any) => {
      //console.log('click', e);
      // //console.log(e.lnglat.lat, e.lnglat.lng);
      const longitude = e.lnglat.lng;
      const latitude = e.lnglat.lat;
      setPosition({ longitude, latitude });
      console.log("position", position);
      // this.getAddressByLngLat(longitude, latitude);
    }
  };

  interface IAMap {
    status: string;
    regeocode: {
      // 格式化后的地址(省市区镇)
      formatted_address: string;
      addressComponent: {
        adcode: string; //地区编码
        //国家,省 市 区 城镇
        country: string;
        province: string;
        city: string;
        district: string;
        township: string;
      };
    };
  }

  // 插件列表,如果需要则将注释放开
  const plugins: Array<PluginList | PluginConfig> = [
    // "MapType",
    // "Scale",
    // "OverView",
    // {
    //   name: "ToolBar",
    //   options: {
    //     visible: true, // 不设置该属性默认就是 true
    //     onCreated(_: any) {
    //       // //console.log(ins);
    //     }
    //   }
    // }
  ];

  React.useEffect(() => {
    console.log("position改变了", position);
    if (!position) {
      return;
    }
    Axios.get(
      `https://restapi.amap.com/v3/geocode/regeo?key=8325164e247e15eea68b59e89200988b&location=${position.longitude},${position.latitude}`
    ).then((res: AxiosResponse) => {
      console.log("res", res);
      if (res.status !== 200) {
        message.error("请求失败,请检查网络");
        return;
      }
      const data: IAMap = res.data;
      if (data.status !== "1") {
        message.error("地图Key已过期，请联系管理员");
        return;
      }
      // 获取经纬度对应的地址信息
      callback({
        ...position,
        address: data.regeocode.formatted_address,
        adcode: data.regeocode.addressComponent.adcode
      });
    });
  }, [position]);

  return (
    <div style={{ height, width }}>
      <Map
        loading={
          <div style={{ textAlign: "center" }}>
            <Spin size='large'>地图加载中，请稍等</Spin>
          </div>
        }
        viewMode='3D'
        plugins={plugins}
        events={mapEvents}
        zoom={4} //缩放级别
        amapkey={"d137aa084e34261f338f583524ff7084"}
        center={position}
        version='1.4.15'>
        {/* // icon是一个图片链接:icon='http://localhost:3000/favicon.png' */}
        <Marker draggable={true} visible={true} position={position} />
        <Input
          placeholder='搜索'
          id='searchInput'
          style={{ position: "absolute", top: "10px", left: "10px", width: "200px" }}
        />
        <Autocomplete
          options={{ input: "searchInput" }}
          onSelect={(e: any) => {
            console.log("e", e);
            if (e.poi.location) {
              const longitude = e.poi.location.lng;
              const latitude = e.poi.location.lat;
              setPosition({ longitude, latitude });
            } else {
              message.error("地图出错,请联系管理员!");
              return false;
            }
          }}
          placeholder='搜索'
        />
      </Map>
    </div>
  );
};
export default AMap;
